var prefix = ctx + "md/job";
var sennum = 1;
$().ready(function() {
	validateRule();
	selectJobType();
	loadSen();
	$(".source-second-select").chosen({
	});
	$(".target-second-select").chosen({
	});
	$(".source-third-select").chosen({
	});
	$(".technical-select").chosen({});
});

$.validator.setDefaults({
	submitHandler : function() {
		update();
	}
});

function  loadSen(){
	
	var sourceMetaType = $("#sourceMetaType").val();
	var tableId = $("#sourceTable").val();
	if (null == tableId) {
		tableId = $("#hSourceTable").val();
	}
	$.ajax({
		url : prefix + '/getColumn/'+sourceMetaType+"/"+tableId,
		success : function(data) {
			var senString = $("#columnRelation").val();
			var arr = []; 
			if(senString ==''){
			 	return false;
			}
			arr = JSON.parse(senString);
			var temp  = "";
			for(var i = 0 ;i < arr.length ; i++){
				
				var tempOption = '<option value="">--请选择字段--</option>';
				for (var j = 0; j < data.length; j++) {
					if (data[j].columnName == arr[i].sc) {
						tempOption += '<option value="' + data[j].columnName + '" selected=\'selected\'>' +  data[j].columnName 
						+((data[j].columnComment == null || data[j].columnComment == "")?"":" ("+data[j].columnComment+") ")
						+ '</option>'
					} else {
						tempOption += '<option value="' + data[j].columnName + '">' +  data[j].columnName 
						+((data[j].columnComment == null || data[j].columnComment == "")?"":" ("+data[j].columnComment+") ")
						+ '</option>'
					}
				}
				
				temp  +="<tr class='jobTr"+sennum+"' >"
				+"<td>"+sennum+"</td>"
				+"<td >"
				+"<select class='source-third-select' >"
				+ tempOption
				+"</td>"
				+"<td >"
				+"<input class='target-column-name' value='"+arr[i].tc+"' readonly='readonly'>"
				+"</td>"
				+"<td >"
				+arr[i].desc
				+"</td>"
				+"</tr>";
				
				sennum ++;
			}
			$("#jobTableforSen").append(temp);
			
		}
	});
}

function update() {
	var jobType = $("#jobType").val();
	if(jobType == '2'){ //同步作业
		var sourceMetaType = $("#sourceMetaType").val();
		if (sourceMetaType == '') {
			layer.msg("请选择源表类型");
			return;
		}
		var sourceTable = $("#sourceTable").val();
		if (sourceTable == '') {
			layer.msg("请选择源表");
			return;
		}
		var targetMetaType = $("#targetMetaType").val();
		if (targetMetaType == '') {
			layer.msg("请选择目标表类型");
			return;
		}
		var targetTable = $("#targetTable").val();
		if (targetTable == '') {
			layer.msg("请选择目标表");
			return;
		}
		
		var arr = [];
		var trs =  $("#jobTableforSen").find("tr");
		var sourceColumnSelected = false;
		trs.each(function(i,k){
    		var $tr = $(k);
    		var json = {sc:"",
    					tc:""};
    		 json.sc = $tr.find(".source-third-select").val();
    		 if (json.sc != '') {
    			 sourceColumnSelected = true;
    		 }
    		 json.tc = $tr.find(".target-column-name").val();
    		 arr.push(json);
    	});
		if (!sourceColumnSelected) {
			layer.msg("请选择源表字段");
		 }
		var jsonArr = JSON.stringify(arr);
		$("#columnRelation").val(jsonArr);
	}
	$.ajax({
		cache : true,
		type : "POST",
		url :prefix + "/doEdit",
		data : $('#signupForm').serialize(),
		async : false,
		error : function(request) {
			laryer.alert("Connection error");
		},
		success : function(data) {
			if (data.code == 0) {
				parent.layer.msg("保存成功");
				parent.reLoad();
				var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
				parent.layer.close(index);

			} else {
				parent.layer.alert(data.msg)
			}
		}
	});
}
function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
		rules : {
			name : {
				required : true
			}
		},
		messages : {
			name : {
				required : icon + "请输入姓名"
			}
		}
	})
}

$('.job-type-select').on('change', function(e, params) {
	selectJobType();
});

function selectJobType(){
	var jobType = $("#jobType").val();
	if (3 == jobType) {
		$("#qiccClass").show();
		$("#taskClass").hide();
		$("#dataSync").hide();
		$("#jobTableforSen").empty();
		
		sourceColumnFlag = false;
		targetColumnFlag = false;
		
		loadTechnicalTable();
	} else if (2 == jobType) {
		$("#taskClass").hide();
		$("#qiccClass").hide();
		$("#dataSync").show();
		loadSourceTable();
		loadTargetTable();
		$("#jobTableforSen").empty();
		
		sourceColumnFlag = false;
		targetColumnFlag = false;
	} else {
		$("#taskClass").show();
		$("#dataSync").hide();
		$("#qiccClass").hide();
		$("#jobTableforSen").empty();
		
		sourceColumnFlag = false;
		targetColumnFlag = false;
	}
	$('.target-first-select').off('change').on('change', function(e, params) {
		$("#jobTableforSen").empty();
		loadTargetTable();
	});
}

function loadSourceTable() {
	var sourceMetaType = $("#sourceMetaType").val();
	var html = '<option value="">--选择源表--</option>';
	$.ajax({
		url : prefix + '/getTable/'+sourceMetaType,
		success : function(data) {
			//加载数据
			for (var i = 0; i < data.length; i++) {
				html += '<option value="' + data[i].tableId + '">' + data[i].tableName 
				+((data[i].tableComment == null || data[i].tableComment == "")?'' : ' ('+data[i].tableComment+') ')
				+ '</option>'
				
			}
			$(".source-second-select").html(html);
			$(".source-second-select").chosen('destroy').chosen({
				search_contains: true,
				maxHeight : 200
			});
			//点击事件
			$(".source-second-select").val($("#hSourceTable").val());
			$(".source-second-select").trigger("chosen:updated");
			
			$('.source-second-select').off('change').on('change', function(e, params) {
				loadSourceColumn();
			});
			
			$(".source-third-select").html('<option value="">--请选择字段--</option>');
			$(".source-third-select").chosen('destroy').chosen({
				search_contains: true,
				maxHeight : 200
			});
		}
	});
}
function loadTargetTable() {
	var targetMetaType = $("#targetMetaType").val();
	var html = '<option value="">--选择目标表--</option>';
	$.ajax({
		url : prefix + '/getTable/'+targetMetaType,
		success : function(data) {
			//加载数据
			for (var i = 0; i < data.length; i++) {
				html += '<option value="' + data[i].tableId + '">' + data[i].tableName 
				+((data[i].tableComment == null || data[i].tableComment == "")?"":" ("+data[i].tableComment+") ")
				+ '</option>'
			}
			$(".target-second-select").html(html);
			$(".target-second-select").chosen('destroy').chosen({
				search_contains: true,
				maxHeight : 200
			});
			//点击事件
			$(".target-second-select").val($("#hTargetTable").val());
			$(".target-second-select").trigger("chosen:updated");
			//loadSourceColumn();
			
			$('.target-second-select').off('change').on('change', function(e, params) {
				
				$("#jobTableforSen").html('');
				var targetMetaType = $("#targetMetaType").val();
				var tableId = $("#targetTable").val();
				$.ajax({
					url : prefix + '/getColumn/'+targetMetaType+"/"+tableId,
					success : function(data) {
						sennum = 1;
						//加载数据
						for (var i = 0; i < data.length; i++) {
							addSen(data[i].columnName,data[i].columnComment);
						}
						
						loadSourceColumn();
					}
				});
				
				
			});
		}
	});
	
}

var sourceColumnHtml = '';
function loadSourceColumn() {
	var targetTable = $("#targetTable").val();
	if (null == targetTable || "" == targetTable) {
		return;
	}
	sourceColumnHtml = '<option value="">--请选择字段--</option>';
	var sourceMetaType = $("#sourceMetaType").val();
	var tableId = $("#sourceTable").val();
	$.ajax({
		url : prefix + '/getColumn/'+sourceMetaType+"/"+tableId,
		success : function(data) {
			//加载数据
			for (var i = 0; i < data.length; i++) {
				sourceColumnHtml += '<option value="' + data[i].columnName + '">' +  data[i].columnName 
				+((data[i].columnComment == null || data[i].columnComment == "")?"":" ("+data[i].columnComment+") ")
				+ '</option>'
			}
			
			$(".source-third-select").html(sourceColumnHtml);
			$(".source-third-select").chosen('destroy').chosen({
				search_contains: true,
				maxHeight : 200
			});
		}
	});
}

function addSen(targetColumnName,targetColumnComment){
	var temp  = "";
	var name = "test";
	temp  +="<tr class='jobTr"+sennum+"' >"
			+"<td>"+sennum+"</td>"
			+"<td >"
			+"<select class='source-third-select' >"
			+"</td>"
			+"<td>"
			+"<input class='target-column-name' value='"+ targetColumnName +"' readonly='readonly'>"
			+"</td>"
			+"<td>" + targetColumnComment
			+"</td>"
			+"</tr>"
	$("#jobTableforSen").append(temp);
	sennum ++ ;
	$(".source-third-select").chosen({
	});
}

/**
 * 加载技术元数据表表
 * @returns
 */
function loadTechnicalTable(){
	var html = '<option value="">--选择技术表--</option>';
	$.ajax({
		url : prefix + '/getTable/1',
		success : function(data) {
			//加载数据
			$.each(data,function(key,value){
				html += '<option value="' + value.tableId + '">' + value.tableName 
							+((value.tableComment == null || value.tableComment == "")?"":" ("+value.tableComment+") ")
						+ '</option>'
			})
				
			$(".technical-select").html(html);
			$(".technical-select").chosen('destroy').chosen({
				search_contains: true,
				maxHeight : 200
			});
			//点击事件
			$(".technical-select").val($("#htechnicalTable").val());
			$(".technical-select").trigger("chosen:updated");
		}
	});
}
